#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "log.hpp"

using namespace std;

Log log;
const int size = 4096;
const char* pathname = "/home/zzy";
const int proj_id = 0x6666;

key_t GetKey()
{
    key_t k = ftok(pathname, proj_id);
    if (k < 0)
    {
        log(Fatal, "ftok error: %s", strerror(errno));
        exit(1);
    }
    return k;
}

int GetShmHelper(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k, size, flag);
    if (shmid < 0)
    {
        log(Fatal, "create share memory error: %s", strerror(errno));
        exit(2);
    }
    log(Info, "create share memory success, shmid: %d", shmid);
    return shmid;
}

int CreateShm()
{
    return GetShmHelper(IPC_CREAT|IPC_EXCL|0666);
}

int GetShm()
{
    return GetShmHelper(IPC_CREAT);
}

#define FIFO_FILE "./myfifo"
#define MODE 0664

enum{
    FIFO_CREAT_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR,
};

class Init
{
public:
    Init()
    {
        int n = mkfifo(FIFO_FILE, MODE);
        if (n < 0)
        {
            log(Fatal, "mkfifo error: %s", strerror(errno));
            exit(FIFO_CREAT_ERR);
        }
    }

    ~Init()
    {
        int n = unlink(FIFO_FILE);
        if (n < 0)
        {
            log(Fatal, "unlink error: %s", strerror(errno));
            exit(FIFO_DELETE_ERR);
        }
    }
};
#endif